package com.ruoyi.exam.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.result.Result;
import com.ruoyi.exam.domain.Question;
import com.ruoyi.exam.domain.TextContent;
import com.ruoyi.exam.domain.enums.QuestionTypeEnum;
import com.ruoyi.exam.domain.question.QuestionObject;
import com.ruoyi.exam.service.IQuestionService;
import com.ruoyi.exam.service.ITextContentService;
import com.ruoyi.exam.utils.*;
import com.ruoyi.exam.viewmodel.admin.question.QuestionEditRequestVM;
import com.ruoyi.exam.viewmodel.admin.question.QuestionPageRequestVM;
import com.ruoyi.exam.viewmodel.admin.question.QuestionResponseVM;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author JY
 * @since 2024-02-19
 */
@Api(tags = "题目表")
@RestController
@RequestMapping("/api/admin/question")
public class QuestionController extends BaseController {
    private String prefix = "/api/admin/question";
    @Resource(name = "QuestionServiceImpl")
    private IQuestionService questionService;

    @Resource(name = "TextContentServiceImpl")
    private ITextContentService textContentService;

    @ApiOperation(value = "分页", notes = "分页查询")
    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public Result pageList(@RequestBody QuestionPageRequestVM model) {

        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        if(model.getLevel() != null && model.getLevel() != 0){
            wrapper.eq("grade_level", model.getLevel());
        }
        if(model.getSubjectId() != null && model.getSubjectId() != 0){
            wrapper.eq("subject_id", model.getSubjectId());
        }
        if(model.getQuestionType() != null && model.getQuestionType() != 0){
            wrapper.eq("question_type", model.getQuestionType());;
        }
        Page<Question> pageQuestion = questionService.page(new Page<>(model.getPageNum(), model.getPageSize()), wrapper);

        List<QuestionResponseVM> collectVm = pageQuestion.getRecords().stream().map(question -> {
            QuestionResponseVM vm = modelMapper.map(question, QuestionResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(question.getCreateTime()));
            vm.setScore(ExamUtil.scoreToVM(question.getScore()));
            TextContent textContent = textContentService.getById(question.getInfoTextContentId());
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(), QuestionObject.class);
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
            vm.setShortTitle(clearHtml);
            return vm;
        }).collect(Collectors.toList());

        Page<QuestionResponseVM> vmPage = new Page<>();
        vmPage.setPages(pageQuestion.getPages());
        vmPage.setCurrent(pageQuestion.getCurrent());
        vmPage.setTotal(pageQuestion.getTotal());
        vmPage.setRecords(collectVm);
        vmPage.setSize(pageQuestion.getSize());

        return Result.ok(vmPage);
    }

    @ApiOperation(value = "编辑", notes = "编辑")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result edit(@RequestBody @Valid QuestionEditRequestVM model) {
        Result validQuestionEditRequestResult = validQuestionEditRequestVM(model);
        if (validQuestionEditRequestResult.getCode() != Result.ok().getCode()) {
            return validQuestionEditRequestResult;
        }

        if (null == model.getId()) {
            questionService.insertFullQuestion(model, getUserId().intValue());
        } else {
            questionService.updateFullQuestion(model);
        }

        return Result.ok();
    }

    @RequiresPermissions("system:question:view")
    @GetMapping()
    public String question() {
        return prefix + "/question";
    }

    @PostMapping(value = "/select/{id}")
    @ApiOperation(value = "查询某个", notes = "查询指定Id")
    public Result<QuestionEditRequestVM> select(@PathVariable Integer id) {
        QuestionEditRequestVM newVM = questionService.getQuestionEditRequestVM(id);
        return Result.ok(newVM);
    }

    @PostMapping(value = "/delete/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    @ApiImplicitParam(name = "id", value = "id",dataTypeClass = Integer.class)
    public Result delete(@PathVariable Integer id) {
        Question question = questionService.getById(id);
        question.setDeleted(true);
        questionService.updateById(question);
        return Result.ok();
    }

    private Result validQuestionEditRequestVM(QuestionEditRequestVM model) {
        int qType = model.getQuestionType().intValue();
        boolean requireCorrect = qType == QuestionTypeEnum.SingleChoice.getCode() || qType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())) {
                String errorMsg = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return Result.fail(errorMsg);

            }
        }

        if (qType == QuestionTypeEnum.GapFilling.getCode()) {
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore)) {
                String errorMsg = ErrorUtil.parameterErrorFormat("score", "空分数和与题目总分不相等");
                return Result.fail(errorMsg);
            }
        }
        return Result.ok();
    }
}

